import { createBrowserRouter, Navigate, redirect } from "react-router-dom";
import { lazy, Suspense } from "react";
import Loading from "@/pages/loading";
import store from "@/store";
const Login = lazy(() => import("@/pages/login"));
const Test = lazy(() => import("@/pages/test"));
const Operate = lazy(() => import("@/pages/operate"));
const NotFound = lazy(() => import("@/pages/404"));
const Layout = lazy(() => import("@/layout"));
const Personnel = lazy(() => import("@/pages/personnel"));
const Hire = lazy(() => import("@/pages/hire"));
const VITE_NO_ACCESS_TOKEN = import.meta.env.VITE_NO_ACCESS_TOKEN;

const router = createBrowserRouter([
  {
    path: "/login",
    loader: () => {
      if (VITE_NO_ACCESS_TOKEN === "true") {
        return null;
      }
      return store.getState().token && store.getState().token !== "null"
        ? redirect("/operate")
        : null;
    },
    element: (
      <Suspense fallback={<Loading />}>
        <Login />
      </Suspense>
    ),
  },
  {
    path: "/",
    loader: () => {
      if (VITE_NO_ACCESS_TOKEN === "true") {
        return null;
      }
      return !store.getState().token || store.getState().token === "null"
        ? redirect("/login")
        : null;
    },
    element: (
      <Suspense fallback={<Loading />}>
        <Layout />
      </Suspense>
    ),
    children: [
      {
        path: "/",
        element: <Navigate to="operate" />,
      },
      {
        path: "operate",
        element: <Operate />,
      },
      {
        path: "personnel",
        element: <Personnel />,
      },
      {
        path: "hire",
        element: <Hire />,
      },
    ],
  },
  {
    path: "/test",
    loader: () => {
      if (VITE_NO_ACCESS_TOKEN === "true") {
        return null;
      }
      return store.getState().token && store.getState().token !== "null"
        ? redirect("/test")
        : null;
    },
    element: (
      <Suspense fallback={<Loading />}>
        <Test />
      </Suspense>
    ),
  },
  {
    path: "*",
    element: (
      <Suspense>
        <NotFound />
      </Suspense>
    ),
  },
]);

export default router;
